//
//  DownloadTool.m
//  MapleLeaf
//
//  Created by WangZe on 15/11/30.
//  Copyright © 2015年 AntennaBabyTeam. All rights reserved.
//

#import "DownloadTool.h"

@implementation DownloadTool


+ (instancetype)shareDownloadTool
{
    static DownloadTool *downloadTool;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        downloadTool = [[DownloadTool alloc] init];
        downloadTool.progressView = [[UIProgressView alloc] init];
        
        
    });
    return downloadTool;
}


- (void)stratDownload:(NSMutableArray *)arr nameStr:(NSString *)str
{
    
    [DownloadTool shareDownloadTool].states = Downloading;
    // 创建队列
    ASINetworkQueue *downloadQueue = [[ASINetworkQueue alloc] init];
    // 清空队列
    [downloadQueue reset];
    
    // 设置支持高精度的进度追踪
    [downloadQueue setShowAccurateProgress:YES];
    
    // 设置代理
    [downloadQueue setDelegate:self];
    
    // 创建progressView;
    
    // 设置队列最大同时下载数
    [downloadQueue setMaxConcurrentOperationCount:3];
    
    
    // 将任务添加到队列里
    for (NSInteger i = 0; i < arr.count; i++) {
        NSURL *url = [NSURL URLWithString:[arr objectAtIndex:i]];
        self.request = [ASIHTTPRequest requestWithURL:url];
        
        // 设置下载路径
        NSString *sandBoxPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
        NSString *docPath = [sandBoxPath stringByAppendingPathComponent:@"Cartoon"];
        NSFileManager *manager = [NSFileManager defaultManager];
        
        // 判断是否存在文件夹
        if (![manager fileExistsAtPath:docPath]) {
            [manager createDirectoryAtPath:docPath withIntermediateDirectories:YES attributes:nil error:nil];
        }
        NSLog(@"%@", docPath);
        [_request setDownloadDestinationPath:[docPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@%ld.zip", str,i]]];
        
        // APP 进入后台继续下载
        [_request setShouldContinueWhenAppEntersBackground:YES];
        
        // 设置userInfo, 可以用来识别不同的request 对象
        [_request setUserInfo:[NSDictionary dictionaryWithObject:[NSString stringWithFormat:@"cartoonRequest"] forKey:@"name"]];
        
        // 失去响应时间
        [_request setTimeOutSeconds:120];
        
        // 设置自动重置次数
        [_request setNumberOfTimesToRetryOnTimeout:3];
        
        [_request setDelegate:self];
        
        [downloadQueue setRequestDidFinishSelector:@selector(DLFAction:)];
        
        
        // 设置代理
//        [self.progressView setProgressViewStyle:UIProgressViewStyleBar];
//        [_request setDownloadProgressDelegate:self.progressView];
        
        
        
        [downloadQueue addOperation:_request];
    }
    
    // 开始队列
    [downloadQueue go];
    // 若要暂停队列 就将队列中所有任务暂停(clearDelegatesAndCancel)
    
}

- (void)DLFAction:(ASINetworkQueue *)quque
{
    [DownloadTool shareDownloadTool].states = Downloaded;
}
- (void)stopDownload
{
    [_request clearDelegatesAndCancel];
}
@end
